///client.c by cme
#include <stdio.h>
#include <string.h>
#include "tcp_sock.h"
int main(int argc, char* argv[])
{
	unsigned short server_port = 2008;
	int nSock = 0;
	int fd = 0;
	int nSend = 0;
	int nBytes;
	char szBuff[8192] = {0};
	//struct sockaddr_in addr;
	if(argc != 3)
	{
		printf("usage:%s destip  filename [port = 2008]\n", argv[0]);
		#ifdef _WIN32
		system("pause");
		#endif
		return 0;
	}
	if(strlen(argv[2]) > 128)
	{
		printf("file name to long\n");
		return 0;
	}
	#ifdef _WIN32
	if((fd = _open(argv[2], O_RDONLY | _O_BINARY)) <= 0)
	#else
	if((fd = open(argv[2], O_RDONLY)) <= 0)
	#endif
	{
		printf("open file %s fail\n", argv[2]);
		return 0;
	}
	init_network();
	nSock = tcp_connect(argv[1], server_port);
	if(nSock <= 0)
	{
		printf("connect to server %s error\n", argv[1]);
		return 0;
	}
	printf("connecting to %s success......\n", argv[1]);
	if(send(nSock, argv[2], strlen(argv[2]), 0) <= 0)
	{
		printf("send file name %s fail\n", argv[2]);
		tcp_close(nSock);
		#ifdef _WIN32
		_close(fd);
		#else
		close(fd);
		#endif
		return 0;
	}
	#ifdef _WIN32
	while((nBytes = _read(fd, szBuff, 8192) ) > 0)
	#else
	while((nBytes = read(fd, szBuff, 8192) ) > 0)
	#endif
	{
		if(send(nSock, szBuff, nBytes, 0) <= 0)
		{
			break;
		}
		memset(szBuff, '\0', 8192);
	}
	#ifdef _WIN32
	_close(fd);
	#else
	close(fd);
	#endif
	tcp_close(nSock);
	printf("sending file %s over\n", argv[2]);
	return 0;
}
